<template>
  <Form ref="form" :model="data" :rules="rules" label-position="top" class="ivu-mt">
    <Row type="flex" :gutter="48">
      <Col >
        <FormItem label="原始密码" prop="phone">
          <Input v-model="data.phone" placeholder="请输入手机号" >
            <Button slot="append" @click="send" >{{message}}</Button>
          </Input>
        </FormItem>
        <FormItem  label="" prop="captchaToken">
          <input type="hidden"  v-model="data.captchaToken"  />
        </FormItem>
        <FormItem label="验证码" prop="captcha">
          <Input v-model="data.captcha" placeholder="请输入手机获取到的验证码" />
        </FormItem>
        <FormItem>
          <Button  @click="handleSubmit">修改密码</Button>
        </FormItem>
      </Col>
    </Row>
  </Form>
</template>

<script>
import {validatorTel} from '@/libs/validator';
import {accountUpdatePhone,sendResetPhoneCaptcha} from '@/api/systemSet'
export default {
  name: "setPassword",
  data(){
    return {
      message:'发送短信',
      data: {
        oldPwd: '',
        newPwd: '',
        surePwd: '',
      },
      rules: {

        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator:validatorTel, trigger: 'blur' }
        ],
        captchaToken: [
          { required: true, message: '请重新发送短信', trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods:{
    tel(value){
      const telStr = /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/;
      return telStr.test(value)
    },
    send(){
      if(this.tel(this.data.phone)){
        this.getToken();
      }else{
        this.$Message.error('请输入正确的手机号')
      }

    },
    async getToken(){
      let res = await sendResetPhoneCaptcha({phone:this.data.phone});
      if(_.get(res,'code')==0){
        this.$Message.success('短信发送成功！')
        this.data.captchaToken=_.get(res,'data');
      }else if(_.get(res,'code')==11002){
        this.$Message.error('验证码已发送，请勿重新发送！')
      }else{
        this.$Message.error('验证码发送失败')
      }
    },
    handleSubmit(){
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if(this.data.newPwd!=this.data.surePwd){
            this.$Message.warning('两次数据的密码必须保持一致')
            return
          }
          let res =await this.update();
          if(res.code==0){
            this.$Message.success('密码更新成功!');
            this.$emit('success',true)
          }else{
            this.$message.error(_.get(res,'message')||'密码修改失败！')
          }

        }
      });
    },
   async update(){
      let {phone,captchaToken,captcha}= this.data
      return await accountUpdatePhone({phone,captchaToken,captcha});
   },
  },
}
</script>

<style scoped>

</style>